<template>
  <div
    v-loading="loading"
    class="rc-cont">
    <flexbox
      class="rc-head"
      justify="space-between">
      <div>
        <wk-toggle-button
          v-model="showType"
          @change="typeChange">
          <wk-toggle-item
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.name"
            :value="item.value">
            {{ item.name }}<i :class="item.icon" />
          </wk-toggle-item>
        </wk-toggle-button>
      </div>

      <flexbox style="width: auto;">
        <el-popover
          v-if="showType === 0"
          v-model="filterShow"
          popper-class="no-padding-popover"
          placement="bottom"
          width="300"
          trigger="click">

          <map-filter
            v-if="filterShow"
            :filter-obj="filterObj"
            :show-type="showType"
            type="enterprise"
            @close="filterShow = false"
            @save="filterSave"
          />

          <el-button
            slot="reference"
            v-model="filterShow"
            :type="filterShow ? 'selected' : 'subtle'"
            icon="wk wk-screening"
            @click="filterShow = true">筛选</el-button>
        </el-popover>

        <el-button
          v-if="$auth('crm.customer.update')"
          style="margin-left: 8px;"
          type="primary"
          @click="relevanceClick">编辑</el-button>
      </flexbox>
    </flexbox>

    <circle-graph
      v-if="showType === 0"
      :id="id"
      ref="circleGraph"
      :key="`circle${refreshKey}`"
      :value="graphData"
      :style="graphStyle"
      :show-type="showType"
      @graph-mouseup="graphMouseup"
      @detail="checkCustomerDetail" />
    <tree-graph
      v-else
      :id="id"
      ref="treeGraph"
      :key="`tree${refreshKey}`"
      :graph-data="graphData"
      :style="graphStyle"
      :show-type="showType"
      @detail="checkCustomerDetail"
    />

    <div class="bottom-panel">
      <span style="margin-right: 15px;"><span class="circle" style="background-color: #f59a23;" />当前客户</span>
      <span><span class="circle" style="background-color: #0052cc;" />相关客户</span>
      <span class="desc"> | 箭头指向说明：上游/上级客户指向下游/下级客户</span>
    </div>

    <relevance-enterprise-dialog
      v-if="relevanceDialogShow"
      :id="id"
      :visible.sync="relevanceDialogShow"
      :data="oneRelationsList"
      @success="relevanceSuccess" />

    <c-r-m-full-screen-detail
      :id="detailId"
      :visible.sync="showFullDetail"
      crm-type="customer"
      @handle="detailHandle" />
  </div>
</template>

<script type="text/javascript">
import { crmCustomerQueryCustomerRelationstListAPI } from '@/api/crm/customer'
import { crmCustomerReadAPI } from '@/api/crm/customer'

import RelevanceEnterpriseDialog from './components/RelevanceEnterpriseDialog'
import MapFilter from './components/MapFilter'
import { WkToggleButton, WkToggleItem } from '@/components/NewCom/WkToggleButton/index'
import CircleGraph from './components/CircleGraph'
import TreeGraph from './components/TreeGraph'

import { objDeepCopy } from '@/utils'

export default {
  name: 'RelationMap', // 关系图谱
  components: {
    CircleGraph,
    TreeGraph,
    RelevanceEnterpriseDialog,
    MapFilter,
    CRMFullScreenDetail: () => import('@/components/CRMFullScreenDetail'),
    WkToggleButton,
    WkToggleItem
  },
  mixins: [],
  inject: ['rootTabs'],
  props: {
    // 模块ID
    id: [String, Number]
  },
  data() {
    return {
      typeOptions: [
        { name: '全部关系', value: 0, icon: 'wk wk-icon-three-line' },
        { name: '上下游关系', value: 1, icon: 'wk wk-icon-org-solid' },
        { name: '上下级关系', value: 2, icon: 'wk wk-icon-org-solid' }],
      graphData: {
        rootId: '',
        nodes: [],
        links: []
      },
      // 直接关系 树结构展示
      oneGraphData: {
        rootId: '',
        nodes: [],
        links: []
      },
      graphStyle: {
        width: 'calc(100% - 10px)',
        height: 'calc(100vh - 400px)',
        marginTop: '5px'
      },

      loading: false,
      filterShow: false, // 筛选显示
      refreshKey: Date.now().toString(),
      showType: 0,
      filterObj: {
        hierarchy: 2,
        relation: 'all',
        customerName: ''
      }, // 筛选数据

      // dialogShow
      relevanceDialogShow: false, // 关联弹框显示
      oneRelationsList: [], // 当前关联关系

      detailId: '',
      showFullDetail: false
    }
  },
  watch: {
    'rootTabs.currentName'(val) {
      if (val === 'relation') {
        this.refreshKey = Date.now().toString()
        this.getGraphData()
      }
    }
  },
  mounted() {
    this.getGraphData()
  },
  methods: {
    /**
     * @description: 类型切换
     * @return {*}
     */
    typeChange() {
      // 延迟一下保证 showType的更新
      this.$nextTick(() => {
        this.filterObj.relation = 'all' // 如果切换大类型，小类型改为全部
        this.filterSave()
        this.filterShow = false
      })
    },

    filterSave(data) {
      if (data) {
        this.filterObj = data
      }
      this.$refs.circleGraph?.filterSave(this.filterObj) // 执行刷新
      this.filterShow = false
    },

    /**
     * 获取图谱数据
     */
    getGraphData() {
      this.loading = true
      crmCustomerQueryCustomerRelationstListAPI({
        customerId: this.id,
        hierarchy: 2,
        relationsId: 0
      })
        .then(res => {
          const node = []
          const nodeIds = []
          let links = []
          // const linksIds = [] // from-id 的字符串

          const resData = res.data || {}
          if (resData.oneRelationsList?.length > 0) {
            resData.oneRelationsList?.forEach(item => {
              this.insertNode(nodeIds, node, item, 'sourceCustomerId', 'sourceCustomerName')
              this.insertNode(nodeIds, node, item, 'targetCustomerId', 'targetCustomerName')

              if ([1, 3].includes(item.type)) { // 上
                // const linkId = `${item.targetCustomerId}-${item.sourceCustomerId}`
                // if (!linksIds.includes(linkId)) {
                //   linksIds.push(linkId)

                links.push({
                  from: item.targetCustomerId,
                  to: item.sourceCustomerId,
                  text: item.relationsName,
                  data: item
                })
                // }
              } else if ([2, 4].includes(item.type)) { // 下
                // const linkId = `${item.sourceCustomerId}-${item.targetCustomerId}`
                // if (!linksIds.includes(linkId)) {
                //   linksIds.push(linkId)
                links.push({
                  from: item.sourceCustomerId,
                  to: item.targetCustomerId,
                  text: item.relationsName,
                  data: item
                })
                // }
              }
            })

            // 一层关系赋值
            // this.oneGraphData = {
            //   rootId: this.id,
            //   nodes: objDeepCopy(node),
            //   links: objDeepCopy(links)
            // }

            resData.twoRelationsList?.forEach(item => {
              this.insertNode(nodeIds, node, item, 'sourceCustomerId', 'sourceCustomerName')
              this.insertNode(nodeIds, node, item, 'targetCustomerId', 'targetCustomerName')

              if ([1, 3].includes(item.type)) { // 上
                // const linkId = `${item.targetCustomerId}-${item.sourceCustomerId}`
                // if (!linksIds.includes(linkId)) {
                //   linksIds.push(linkId)
                links.push({
                  from: item.targetCustomerId,
                  to: item.sourceCustomerId,
                  text: item.relationsName,
                  data: item
                })
                // }
              } else if ([2, 4].includes(item.type)) { // 下
                // const linkId = `${item.sourceCustomerId}-${item.targetCustomerId}`
                // if (!linksIds.includes(linkId)) {
                //   linksIds.push(linkId)
                links.push({
                  from: item.sourceCustomerId,
                  to: item.targetCustomerId,
                  text: item.relationsName,
                  data: item
                })
                // }
              }
            })
            this.oneRelationsList = resData.oneRelationsList || []

            // links 去重
            const linksSet = new Set(links.map(item => JSON.stringify(item)))
            links = Array.from(linksSet).map(item => JSON.parse(item))

            this.graphData = {
              rootId: this.id,
              nodes: objDeepCopy(node),
              links: objDeepCopy(links)
            }
            this.loading = false
          } else {
            this.oneRelationsList = []
            this.getCustomerDetail()
          }
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * @description: 插入Node
     * @param {*} nodeIds 记录是否重复节点
     * @param {*} results 结果输出
     * @param {*} item 数据data
     * @param {*} idKey id 属性名
     * @param {*} textKey 展示 属性名
     * @return {*}
     */
    insertNode(nodeIds, results, item, idKey, textKey) {
      // if (!nodeIds.includes(item[idKey])) {
      //   nodeIds.push(item[idKey])

      // item 增加 relationTypes 存储多种场景
      // item.relationTypes = [item.type]

      results.push({
        id: item[idKey],
        text: item[textKey],
        color: item[idKey] === this.id ? '#f59a23' : '#0052cc',
        data: item
      })
      // } else {
      //   const nodeItem = results.find(obj => obj.id === item[idKey])
      //   if (nodeItem && !nodeItem.data.relationTypes.includes(item.type)) {
      //     nodeItem.data.relationTypes.push(item.type)
      //   }
      // }
    },

    /**
     * @description: 客户详情
     * @return {*}
     */
    getCustomerDetail() {
      this.loading = true
      crmCustomerReadAPI({
        customerId: this.id
      })
        .then(res => {
          this.loading = false
          const resData = res.data || {}

          this.graphData = {
            rootId: this.id,
            nodes: [{
              id: resData.customerId,
              text: resData.customerName,
              color: '#f59a23',
              data: resData
            }],
            links: []
          }
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * @description: 点击其余地方取消聚焦
     * @return {*}
     */
    graphMouseup() {
      this.filterObj = {
        hierarchy: 2,
        relation: 'all',
        customerName: ''
      }
    },

    /**
     * 关联成功
     */
    relevanceSuccess() {
      this.oneRelationsList = []
      this.getGraphData()
      this.relevanceDialogShow = false
    },

    /**
     * 查看客户详情
     */
    checkCustomerDetail(id) {
      this.detailId = id
      this.showFullDetail = true
    },

    detailHandle() {

    },

    /**
     * 关联客户点击
     */
    relevanceClick() {
      this.relevanceDialogShow = true
    }

  }
}
</script>
<style lang="scss" scoped>
.bottom-panel {
  display: flex;
  justify-content: center;

  .circle {
    display: inline-block;
    width: 10px;
    height: 10px;
    margin-right: 5px;
    border-radius: 50%;
  }

  .desc {
    margin-left: 8px;
    color: $--color-text-secondary;
  }
}

.wk-toggle-item {
  display: flex;
  align-items: center;
}
</style>
